/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import DBController.UserDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.UserBean;

/**
 *
 * @author brlnt
 */
public class AkunServlet extends HttpServlet {

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getServletPath();
        HttpSession session = request.getSession();
        UserBean sesiUser = (UserBean) session.getAttribute("sesiUser");
        UserDB userdb;
//        if(path.equals("/deleteakun")){
//            PrintWriter out = response.getWriter();
//            out.println("bisa");
//        }
        if (sesiUser != null) {
            if (path.equals("/kelola_akun")) {
                if (sesiUser.getRole() == 1) {
                    try {
                        List listUser = new UserDB().getAllUser();
                        request.setAttribute("listUser", listUser);
                        request.setAttribute("title", "Kelola Akun");
                        request.getRequestDispatcher("/WEB-INF/view/kelolaakun.jsp").forward(request, response);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(AkunServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (SQLException ex) {
                        Logger.getLogger(AkunServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    response.sendError(401);
                }
            } else if (path.equals("/akun")) {
                request.setAttribute("title", "Edit Profil");
                request.setAttribute("tombol", "Simpan");
                request.setAttribute("alamat", path);
                int id = sesiUser.getIdUser();
                UserBean userdata = new UserDB().getUserByID(id);
                //PrintWriter out = response.getWriter();
                //out.print(userdata.getRole());
                request.setAttribute("editprofil", userdata);
                request.getRequestDispatcher("/WEB-INF/view/edit_akun.jsp").forward(request, response);
            } else if (path.equals("/edit_akun")) {
                if (sesiUser.getRole() == 1) {
                    request.setAttribute("title", "Edit Role");
                    request.setAttribute("tombol", "Ubah Role");
                    request.setAttribute("alamat", path);
                    int id = Integer.valueOf(request.getParameter("id"));
                    UserBean userdata = new UserDB().getUserByID(id);
                    //PrintWriter out = response.getWriter();
                    //out.print(userdata.getRole());
                    request.setAttribute("editadmin", userdata);
                    request.getRequestDispatcher("/WEB-INF/view/register.jsp").forward(request, response);
                } else {
                    response.sendError(401);
                }
            } else if (path.equals("/buat_akun")) {
                if (sesiUser.getRole() == 1) {
                    request.setAttribute("title", "Buat Akun");
                    request.setAttribute("tombol", "Buat");
                    request.setAttribute("alamat", path);
                    request.getRequestDispatcher("/WEB-INF/view/register.jsp").forward(request, response);
                } else {
                    response.sendError(401);
                }
            }
        } else if (sesiUser == null) {
            if (path.equals("/register")) {
                request.setAttribute("title", "Daftar");
                request.setAttribute("tombol", "Daftar");
                request.setAttribute("alamat", path);
                request.getRequestDispatcher("/WEB-INF/view/register.jsp").forward(request, response);
            } else {
                response.sendRedirect("home");
            }
        } else {
            response.sendRedirect("login");
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        UserBean sesiUser = (UserBean) session.getAttribute("sesiUser");
        String path = request.getServletPath();
        if (sesiUser != null) {
            if (path.equals("/buat_akun")) {
                if (sesiUser.getRole() == 1) {
                    tambahAkun(request, response);
                } else {
                    response.sendError(401);
                }
            } else if (path.equals("/deleteakun")) {
                if (sesiUser.getRole() == 1) {
                    hapusAkun(request, response);
                } else {
                    response.sendError(401);
                }
            } else if (path.equals("/edit_akun")) {
                if (sesiUser.getRole() == 1) {
                    int role = Integer.parseInt(request.getParameter("role"));
                    int id = Integer.parseInt(request.getParameter("id"));
                    new UserDB().ubahRole(id, role);
                    response.sendRedirect("kelola_akun");
                } else {
                    response.sendError(401);
                }
            } else if (path.equals("/akun")) {
                UserDB userdb = new UserDB();
                UserBean dataUser = new UserBean();
                dataUser.setFirstName(request.getParameter("namaDepan"));
                dataUser.setLastName(request.getParameter("namaBelakang"));
                dataUser.setEmail(request.getParameter("email"));
                dataUser.setIdUser(sesiUser.getIdUser());
                dataUser.setOldPassword(request.getParameter("password-lama"));
                dataUser.setPassword(request.getParameter("password"));
                if (dataUser.getOldPassword() != null) {
                    if (userdb.cekPassword(dataUser.getIdUser(), dataUser.getOldPassword())) {
                        userdb.editUserWithPass(dataUser);
                        request.setAttribute("messageSuccess", "Password sukses diganti !");
                        request.setAttribute("editprofil", dataUser);
                        request.setAttribute("title", "Edit Profil");
                        request.setAttribute("tombol", "Simpan");
                        request.setAttribute("alamat", path);
                        request.getRequestDispatcher("/WEB-INF/view/edit_akun.jsp").forward(request, response);
                    } else {
                        request.setAttribute("messagePassword", "Password lama yang dimasukkan salah !");
                        request.setAttribute("error", dataUser);
                        request.setAttribute("title", "Edit Profil");
                        request.setAttribute("tombol", "Simpan");
                        request.setAttribute("alamat", path);
                        request.getRequestDispatcher("/WEB-INF/view/edit_akun.jsp").forward(request, response);
                    }
                } else {
                    userdb.editUser(dataUser);
                }
                //dataUser.setRole(Integer.valueOf(request.getParameter("role")));
            }
        } else {
            if (path.equals("/register")) {
                UserDB userdb = new UserDB();
                UserBean dataUser = new UserBean();
                dataUser.setFirstName(request.getParameter("namaDepan"));
                dataUser.setLastName(request.getParameter("namaBelakang"));
                dataUser.setEmail(request.getParameter("email"));
                dataUser.setPassword(request.getParameter("password"));
                dataUser.setRole(Integer.valueOf(request.getParameter("role")));
                if (!userdb.cekEmail(dataUser.getEmail())) {
                    new UserDB().createUser(dataUser);
                    response.sendRedirect("login");
                } else {
                    request.setAttribute("messageEmail", "Email sudah terdaftar");
                    request.setAttribute("error", dataUser);
                    request.setAttribute("title", "Daftar");
                    request.setAttribute("tombol", "Daftar");
                    request.setAttribute("alamat", path);
                    request.getRequestDispatcher("/WEB-INF/view/register.jsp").forward(request, response);
                }
            }
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }

    private void tambahAkun(HttpServletRequest request, HttpServletResponse response) {
        try {
            // get sesi user
            HttpSession session = request.getSession();
            UserBean sesiUser = (UserBean) session.getAttribute("sesiUser");
            // get alamat url yg sedang diakses
            String path = request.getServletPath();

            UserBean dataUser = new UserBean();
            UserDB userdb = new UserDB();
            // set data user
            dataUser.setFirstName(request.getParameter("namaDepan"));
            dataUser.setLastName(request.getParameter("namaBelakang"));
            dataUser.setEmail(request.getParameter("email"));
            dataUser.setPassword(request.getParameter("password"));
            dataUser.setRole(Integer.parseInt(request.getParameter("role")));
            // create user (insert ke db)
            userdb.createUser(dataUser);
            //redirect ke alamat /kelola_akun
            response.sendRedirect("kelola_akun");
        } catch (IOException ex) {
            Logger.getLogger(AkunServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void hapusAkun(HttpServletRequest request, HttpServletResponse response) {
        try {
            int id = Integer.valueOf(request.getParameter("id"));
            new UserDB().deleteUser(id);
            response.sendRedirect("kelola_akun");
        } catch (IOException ex) {
            Logger.getLogger(AkunServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
